<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>手机通讯录管理系统</title>
<style>
.container {
width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: inline-block;
width: 60px;
}
input[type="text"] {
width: 200px;
padding: 5px;
}
button {
margin: 5px;
padding: 6px 12px;
background: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
textarea {
width: 100%;
height: 150px;
margin-top: 10px;
padding: 5px;
resize: vertical;
}
</style>
</head>
<body>
<div class="container">
<div class="form-group">
<label>姓名：</label>
<input type="text" id="nameInput">
</div>
<div class="form-group">
<label>电话：</label>
<input type="text" id="phoneInput">
</div>
<div>
<button onclick="addContact()">添加</button>
<button onclick="searchContact()">查询</button>
<button onclick="deleteContact()">删除</button>
<button onclick="resetForm()">重置</button>
</div>
<textarea id="contactsArea" readonly></textarea>
</div>

<script>
// 初始化存储键名
const STORAGE_KEY = 'phoneBook';

// 初始化时加载已有通讯录
loadContacts();

// 添加联系人
function addContact() {
const name = document.getElementById('nameInput').value.trim();
const phone = document.getElementById('phoneInput').value.trim();

if (!name || !phone) {
alert('姓名和电话不能为空！');
return;
}

const contacts = getContacts();
contacts.push({ name, phone });
localStorage.setItem(STORAGE_KEY, JSON.stringify(contacts));
updateDisplay();
resetForm();
}

// 查询联系人
function searchContact() {
const name = document.getElementById('nameInput').value.trim();
if (!name) return;

const contacts = getContacts();
const found = contacts.find(c => c.name === name);

if (found) {
document.getElementById('phoneInput').value = found.phone;
} else {
alert('未找到该联系人！');
}
}

// 删除联系人
function deleteContact() {
const name = document.getElementById('nameInput').value.trim();
if (!name) return;

let contacts = getContacts();
const newContacts = contacts.filter(c => c.name !== name);

if (contacts.length !== newContacts.length) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(newContacts));
updateDisplay();
resetForm();
alert('删除成功！');
} else {
alert('未找到该联系人！');
}
}

// 重置表单
function resetForm() {
document.getElementById('nameInput').value = '';
document.getElementById('phoneInput').value = '';
}

// 获取所有联系人
function getContacts() {
const data = localStorage.getItem(STORAGE_KEY);
return data ? JSON.parse(data) : [];
}

// 更新显示区域
function updateDisplay() {
const contacts = getContacts();
const displayText = contacts
.map(c => `${c.name}: ${c.phone}`)
.join('\n');
document.getElementById('contactsArea').value = displayText;
}

// 初始化加载通讯录
function loadContacts() {
updateDisplay();
}
</script>
</body>
</html>